package com.bite.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bite.blog.common.exception.BlogException;
import com.bite.blog.common.pojo.dataobject.BlogInfo;
import com.bite.blog.common.pojo.dataobject.UserInfo;
import com.bite.blog.common.pojo.request.UserLoginParam;
import com.bite.blog.common.pojo.response.UserInfoResponse;
import com.bite.blog.common.pojo.response.UserLoginResponse;
import com.bite.blog.common.utils.BeanConver;
import com.bite.blog.common.utils.JwtUtil;
import com.bite.blog.common.utils.SecurityUtil;
import com.bite.blog.mapper.BlogInfoMapper;
import com.bite.blog.mapper.UserInfoMapper;
import com.bite.blog.service.UserService;
import io.jsonwebtoken.Jwts;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Resource(name = "userInfoMapper")
    private UserInfoMapper userInfoMapper;

    @Resource(name = "blogInfoMapper")
    private BlogInfoMapper blogInfoMapper;

    @Override
    public UserLoginResponse login(UserLoginParam userParam) {
        //判断用户是否存在
        //根据用户名, 去查询用户信息
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserName, userParam.getUserName()).eq(UserInfo::getDeleteFlag, 0));
        if (userInfo==null){
            throw new BlogException("用户不存在");
        }
        //用户存在, 校验密码是否正确
        if (!SecurityUtil.verify(userParam.getPassword(), userInfo.getPassword())){
            throw new BlogException("密码错误");
        }
        //密码正确
        UserLoginResponse response = new UserLoginResponse();
        response.setUserId(userInfo.getId());
        //载荷
        Map<String, Object> map = new HashMap<>();
        map.put("id", userInfo.getId());
        map.put("name", userInfo.getUserName());
        response.setToken(JwtUtil.genToken(map));
        return response;
    }

    @Override
    public UserInfoResponse getUserInfoById(Integer userId) {
        UserInfo userInfo = selectUserInfoById(userId);
        return BeanConver.trans(userInfo);
    }

    @Override
    public UserInfoResponse getAuthorInfo(Integer blogId) {
        //1. 根据博客id, 拿到作者id
        BlogInfo blogInfo = blogInfoMapper.selectOne(new LambdaQueryWrapper<BlogInfo>()
                .eq(BlogInfo::getId, blogId).eq(BlogInfo::getDeleteFlag, 0));
        //2. 根据作者id, 拿到作者详情
        if (blogInfo==null){
            throw new BlogException("博客不存在");
        }
        UserInfo userInfo = selectUserInfoById(blogInfo.getUserId());
        return BeanConver.trans(userInfo);
    }

    public UserInfo selectUserInfoById(Integer userId){
        return userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getId, userId).eq(UserInfo::getDeleteFlag, 0));
    }
}
